package rad.framework.jsf;

import java.io.IOException;

import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.el.ValueBinding;

public class HtmlFieldset extends UIComponentBase {

	public static final String COMPONENT_FAMILY = "rad.framework.jsf.HtmlFieldset";

	public static final String COMPONENT_TYPE = "rad.framework.jsf.HtmlFieldset";

	private String legend;

	@Override
	public String getFamily() {
		return COMPONENT_FAMILY;
	}

	public String getLegend() {
		return legend;
	}

	public void setLegend(String legend) {
		this.legend = legend;
	}

	@Override
	public void restoreState(FacesContext context, Object state) {
		Object[] values = (Object[]) state;
		super.restoreState(context, values[0]);
		legend = (String) values[1];
	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] values = new Object[2];
		values[0] = super.saveState(context);
		values[1] = legend;
		return values;
	}

	@Override
	public void encodeBegin(FacesContext context) throws IOException {
		if (!isRendered())
			return;

		super.encodeBegin(context);
		ResponseWriter response = context.getResponseWriter();
		response.startElement("fieldset", this);

		response.writeAttribute("id", getClientId(context), "id");

		ValueBinding classBinding = getValueBinding("legend");
		String legend = classBinding == null ? this.legend
				: (String) classBinding.getValue(context);
		if (legend != null) {
			response.startElement("legend", this);
			response.write(legend);
			response.endElement("legend");
		}
	}

	@Override
	public void encodeEnd(FacesContext context) throws IOException {
		if (!isRendered())
			return;

		ResponseWriter response = context.getResponseWriter();
		response.endElement("fieldset");
		response.flush();
		super.encodeEnd(context);
	}

}
